package com.macro.mall.aspect;

import com.macro.mall.annotation.ShowAccountId;
import com.macro.mall.util.EncryptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author jicai 2021-09-17
 */
@Aspect
@Component
@Order(0)
@Slf4j
public class ShowAccountIdAspect {

    private static final String TOKEN              = "token";


    @Around(value = "@annotation(showAccountId)")
    public Object turingAuth(ProceedingJoinPoint joinPoint, ShowAccountId showAccountId) throws Throwable {
        HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 解析accountId
        Long accountId = getAccountId(request);

        // 赋值authData
        Object[] params = joinPoint.getArgs();
        for (int i = 0; i < params.length; i ++) {
            Object object = params[i];
            if(object instanceof Long){
                params[i] = accountId;
                break;
            }
        }

        return joinPoint.proceed(params);
    }

    /********************************************** 以下私有方法  **********************************************************/

    private Long getAccountId(HttpServletRequest request){
        try {
            String idStr = request.getHeader(TOKEN);
            return EncryptionUtil.aesDecrypt(idStr);
        }catch (Exception e){
            return null;
        }
    }

}
